package com.news.cloud.service;

import com.news.cloud.exception.ServerTechnicalException;
import com.news.cloud.jpa.domain.Gender;
import com.news.cloud.jpa.domain.User;
import com.news.cloud.jpa.repository.UserRepository;
import com.news.cloud.web.model.UserPageResponse;
import com.news.cloud.web.model.UserResponse;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * Created by hiephn on 2014/07/12.
 */
@Service
public class UserService extends AbstractService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private UserRepository userRepo;

    private SimpleDateFormat fbBirthDayDateFormat = new SimpleDateFormat("MM/dd/yyyy");

    public UserPageResponse get(int id, String name, String fullName, int page, int pageSize)
            throws ServerTechnicalException {
        if (id > 0) {
            User user = userRepo.findOne(id);
            UserPageResponse userPageResponse = new UserPageResponse();
            userPageResponse.from(user, UserResponse.class);
            return userPageResponse;
        } else {
            Page<User> userPage = userRepo.findByNameLikeOrFullNameLike(
                    StringUtils.isEmpty(name) ? "%" : "%" + name + "%",
                    StringUtils.isEmpty(fullName) ? "%" : "%" + fullName + "%",
                    new PageRequest(page, pageSize)
            );
            UserPageResponse userPageResponse = new UserPageResponse();
            userPageResponse.from(userPage, UserResponse.class);
            return userPageResponse;
        }
    }

    public UserResponse create(String name, String fullName, String password, String desc, String email,
                               long birthDayLong, String phone) {
        return null;
    }

    public User updateFb(String name, String birthdayString, String email, String genderString,
                                 String updatedTime, String accessToken, String id, String imgUrl) {
        User user = userRepo.findOneByEmail(StringUtils.lowerCase(email));
        if (user != null && StringUtils.equals(updatedTime, user.getFbUpdatedTime())) {
            user.setFbAccessToken(accessToken);
            return user;
        } else if (user == null) {
            user = new User();
            user.setEmail(StringUtils.lowerCase(email));
            userRepo.save(user);
        }

        Timestamp birthDay = null;
        try {
            birthDay = new Timestamp(fbBirthDayDateFormat.parse(birthdayString).getTime());
        } catch (ParseException e) {
            LOGGER.error("Cannot parse user birthday: " + birthdayString, e);
        }
        Gender gender = null;
        try {
            gender = Gender.valueOf(StringUtils.lowerCase(genderString));
        } catch (Exception e) {
            LOGGER.error("Cannot parse gender: " + genderString, e);
        }
        user.setBirthday(birthDay);
        user.setName(id);
        user.setFullName(name);
        user.setEmail(email);
        user.setGender(gender);
        user.setFbUpdatedTime(updatedTime);
        user.setFbAccessToken(accessToken);
        user.setImgUrl(imgUrl);

        return user;
    }
}
